'''
Author: asdefwe 535294621@qq.com
Date: 2024-05-19 23:54:04
LastEditors: asdefwe 535294621@qq.com
LastEditTime: 2024-05-22 21:12:36
FilePath: \图片\Font.py
Description: 

Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
'''
from PIL import Image  
  
def extract_font_bitmap(image_path):  
    # 打开图像并转换为1位（黑白）模式  
    image = Image.open(image_path).convert('L')  
      
    # 创建一个列表来保存字模  
    font = []  
      
    # 遍历字符区域  
    for y in range(image.height):  
        row = []  
        for x in range(image.width):  
            # 获取像素值（0为白色，1为黑色）  
            pixel_value = image.getpixel((x, y))   
            row.append(pixel_value)  
        font.append(row)  
      
    return font  


def gray_to_RGB():
    # 打开灰度图
    gray_image = Image.open('path_to_gray_image.jpg')

    # 确保图像是灰度模式
    if gray_image.mode != 'L':
        gray_image = gray_image.convert('L')

    # 将灰度图转换为RGB
    rgb_image = gray_image.convert('RGB')

    # 创建一个新的图像，用于存储RGB565格式的数据
    rgb565_image = Image.new('RGB', rgb_image.size)

    # 获取原图的像素数据
    pixels = rgb_image.load()

    # 遍历每个像素，将其转换为RGB565格式
    for i in range(rgb_image.size[0]):  # 遍历宽度
        for j in range(rgb_image.size[1]):  # 遍历高度
            # 灰度值直接用作RGB的每个分量
            gray_value = pixels[i, j][0]

            # 将8位灰度值映射到RGB565
            r = (gray_value >> 3) & 0x1F
            g = (gray_value >> 2) & 0x3F
            b = (gray_value >> 3) & 0x1F

            # 合并各颜色分量到一个16位的值中
            rgb565 = (r << 11) | (g << 5) | b

            # 将RGB565的值转换为RGB元组
            r = (rgb565 >> 11) & 0x1F
            g = (rgb565 >> 5) & 0x3F
            b = rgb565 & 0x1F

            # 将5位/6位的值扩展到8位，以便可以在标准的RGB图像中表示
            r = (r << 3) | (r >> 2)
            g = (g << 2) | (g >> 4)
            b = (b << 3) | (b >> 2)

            # 设置转换后的像素值
            rgb565_image.putpixel((i, j), (r, g, b))


def print_list(piclist):
    # 计算每一列的最大宽度
    col_widths = [max(len(str(piclist[row][col])) for row in range(len(piclist))) for col in range(len(piclist[0]))]

    # 创建格式化字符串
    format_str = ' '.join('{{:^{}}}'.format(width) for width in col_widths)

    # 打印格式化后的数据
    for row in piclist:
        print(format_str.format(*row))


def Save_C(FontName, pixels):
    # 使用.format()方法
    c_array_str = 'const unsigned char Font_{}[] = {{\n    '.format(FontName)

    # 设置每行显示的像素数以保持格式整洁
    pixels_per_line = 9
    line_pixel_count = 0

    # 格式化每个像素值并添加到C数组字符串中
    for row in pixels:
        for pixel in row:
            c_array_str += '0x{:02x}, '.format(pixel)
            line_pixel_count += 1
            # 换行
            if line_pixel_count == pixels_per_line:
                c_array_str += '\n    '
                line_pixel_count = 0

    # 如果字符串不是以换行符结束的，则添加一个数组结束符和换行符
    if not c_array_str.endswith('\n'):
        c_array_str += '\r'

    # 结束C数组字符串
    c_array_str += '};'

    # 打印或保存C数组字符串
    print(c_array_str)


if __name__ == '__main__':
    picname = "1-9-11"
    # 保存8*9英文单词
    font_code = extract_font_bitmap('image/{}.png'.format(picname))  
    print_list(font_code)
    Save_C(picname, font_code)